<template>
  <div>
    <el-container>
      <el-header>
      </el-header>

      <el-main>
        <el-table
            ref="multipleTable"
            :data="tableData"
            tooltip-effect="dark"
            style="width: 100%"
            @selection-change="handleSelectionChange">
          <el-table-column
              type="selection"
              width="55">
          </el-table-column>
          <el-table-column
              prop="picture"
              label=""
              width="120">
            <template slot-scope="scope"><img style="width: 70px;" :src="scope.row.picture"></template>
          </el-table-column>
          <el-table-column
              prop="bookName"
              label="商品"
              width="240"
          >
            <template slot-scope="scope">{{ scope.row.bookName }}</template>
          </el-table-column>
          <el-table-column

              prop="degree"
              label="品相"
              width="120">
            <template slot-scope="scope">{{ scope.row.degree }}</template>
          </el-table-column>
          <el-table-column
              prop="price"
              label="单价"
              width="120"
              show-overflow-tooltip>
            <template slot-scope="scope">{{ scope.row.price }}</template>
          </el-table-column>
          <el-table-column
              prop="count"
              label="数量"
              width="200"
              @cuechange="cuechange"
              show-overflow-tooltip>
            <template slot-scope="scope">
              <el-input-number @change="handleChange(scope.row)" size="mini" v-model="scope.row.count"
                               :step="1"></el-input-number>
            </template>
            <!--            <template slot-scope="scope">{{ scope.row.count }}</template>-->
          </el-table-column>
          <el-table-column
              prop="amount"
              label="金额"
              width="120"
              show-overflow-tooltip>
            <template slot-scope="scope">{{ scope.row.amount = (scope.row.price * scope.row.count).toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column
              prop=""
              label="操作"
              show-overflow-tooltip>
            <template slot-scope="scope">
              <a href="" style="text-decoration: none;font-size: 12px;color: black">移入收藏夹</a> <br>
              <a @click="deleteById(scope.row.id)" href="javascript:void (0)"
                 style="text-decoration: none;font-size: 12px;color: black">删除</a>
            </template>
          </el-table-column>
        </el-table>
        <div style="margin-top: 20px;height: 50px;; background-color: gainsboro;border-radius: 5px">

          <el-button @click="toggleSelection()" style="height: 50px">取消选择</el-button>
          <span style="position: relative; left: 400px"> 已选 {{ checkCount }} 件商品</span>
          <span style="position: relative; left: 400px"> 合计(不含运费): ¥ {{ allPrices }}</span>


          <el-button @click="pay" style="background-color: chocolate;color: white;float: right;height: 50px;margin: 0">
            去结算
          </el-button>

        </div>

        <!-- Form -->
        <el-dialog title="登录" :visible.sync="dialogFormVisible">
          <el-form :model="form">
            <el-form-item label="用户名" :label-width="formLabelWidth">
              <el-input v-model="form.username" style="width: 70%" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="密码" :label-width="formLabelWidth">
              <el-input v-model="form.password" style="width: 70%" autocomplete="off"></el-input>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="toLogin">登 录</el-button>
          </div>
        </el-dialog>

      </el-main>
    </el-container>
  </div>
</template>

<script>

import {mapMutations, mapState} from "vuex";
import axios from "axios";
import router from "@/router";

export default {
  name: "ShopView",
  data() {
    return {
      /*登录表单*/
      dialogFormVisible: false,
      form: {
        username: '',
        password: ''
      },
      formLabelWidth: '30%',
      /*数据*/
      checkCount: 0,
      allPrices: 0,
      num: 0,
      tableData: [],
      multipleSelection: []
    }
  },
  computed: {
    ...mapState(["userId", "isLogin"])
  },
  mounted() {
    if (this.isLogin) {
      this.updateCartList()
    } else {
      this.updateCartListByBookIds()
    }
    console.log(this.tableData)
  },
  methods: {
    ...mapMutations(["setUser", "setIsLogin", "setUserId"]),
    toLogin() {
      //登录，设置uid token到本地，保存 user 数据
      axios.post("/user/login", this.form).then(r => {
        if (r.data.state === 20000) {
          /*登录成功后把 jwt 保存*/
          console.log("登录数据")
          console.log(r.data.data)
          localStorage.setItem("Authentication", r.data.data.longinJwtStr)
          localStorage.setItem("uid", r.data.data.id)
          this.setUserId(r.data.data.id)
          this.setIsLogin(true)
          console.log(this.isLogin)
          //获取头像、昵称
          console.log("获取头像昵称请求中 userId ： " + this.userId)
          axios.get("/user/menuSource/" + this.userId).then(r => {
            let data = {nick: '', phone: '', email: '', avatar: ''}
            data.nick = r.data.data.nick
            data.avatar = r.data.data.avatar
            this.setUser(data)
            //登录成功后合并本地购物车数据到服务器
            this.mergeLocalCart()
            //删除本地购物车数据
            localStorage.removeItem("cartTemp")
            this.$message.success("登录成功")
          }).catch(e => console.log(e))
        } else {
          this.$message.error(r.data.message)
        }
        this.dialogFormVisible = false
      }).catch(e => console.log(e))
    },
    //合并本地购物车到数据库
    mergeLocalCart() {
      let localCart = JSON.parse(localStorage.getItem("cartTemp"))
      if (localCart==null){
        return
      }
      console.log("向服务器发送 localCart 数组")
      console.log(localCart)
      //需要数据：书名、价格、图片、数量
      axios.post("/cart/getCartList", localCart).then(r => {
        if (r.data.state === 20000) {
          console.log("服务器发来购物车数据：")
          let carts = r.data.data
          for (let i = 0; i < localCart.length; i++) {
            carts[i].bookId = localCart[i].bookId
          }
          console.log(carts)
          console.log("处理后其作为参数发给服务器合并购物车")
          axios.post("/cart/mergeLocalCart/" + this.userId,carts).then(r => {
            if (r.data.state === 20000) {
              console.log("成功合并本地购物车数据到服务器，清理本地购物车数据")
              localStorage.removeItem("cartTemp")
            } else {
              this.$message.error("合并本地购物车数据到服务器 失败")
            }
          })
        }
      }).catch(e => console.log(e))
    },
    //通过用户ID刷新购物车数据
    updateCartList() {
      let userId = parseInt(this.userId)
      axios.get("/cart/getCartList/" + userId).then(r => {
        console.log("服务器返回用户购物车数据：")
        console.log(r.data.data)
        this.tableData = r.data.data;
      }).catch(e => console.log(e))
    },
    //未登录状态下通过 图书ID数组 批量获取购物车图书数据
    updateCartListByBookIds() {
      let localCart = JSON.parse(localStorage.getItem("cartTemp"))
      if (localCart==null){
        return
      }
      console.log("向服务器发送 localCart 数组")
      console.log(localCart)
      //需要数据：书名、价格、图片、数量
      axios.post("/cart/getCartList", localCart).then(r => {
        if (r.data.state === 20000) {
          console.log("服务器发来购物车数据：")
          this.tableData = r.data.data
        }
      }).catch(e => console.log(e))
    },
    pay() {
      if (this.multipleSelection.length===0){
        this.$message.warning("请选中要结算的商品哦")
        return
      }
      console.log("当前选中：")
      console.log(this.multipleSelection)
      console.log("当前登录状态：")
      console.log(this.isLogin)
      if (!this.isLogin) {
        //打开登录表单
        this.dialogFormVisible = true
        return
      }
      console.log("支付待实现")
      let orderTemp = JSON.stringify(this.multipleSelection)
      localStorage.setItem("orderTemp", orderTemp)
      console.log(JSON.parse(localStorage.getItem("orderTemp")))
      router.push("/buy")
    },
    cuechange(currentRow, oldCurrentRow) {
      console.log(currentRow)
      console.log(oldCurrentRow)
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    //选中商品时
    handleSelectionChange(val) {
      this.multipleSelection = val;
      this.resetAllPrices()
    },
    //刷新统计栏的 数量和总金额
    resetAllPrices() {
      let p = 0
      for (let valKey of this.multipleSelection) {
        p += (valKey.count * valKey.price)
      }
      this.allPrices = p.toFixed(2)
      this.checkCount = this.multipleSelection.length
      console.log(this.multipleSelection)
    },
    //单个商品数量变化改变对应选中列表中该商品的数量
    handleChange(item) {
      console.log(this.tableData.amount)
      for (let valKey of this.multipleSelection) {
        if (valKey.id === item.id) {
          valKey.count = item.count
        }
      }
      this.resetAllPrices()
    },
    deleteById(id) {
      console.log("删除购物车ID为：" + id + " 的数据")
      axios.delete("/cart/deleteById/" + id).then(r => {
        if (r.data.state === 20000) {
          this.$message.success("删除成功");
          this.updateCartList()
        }
      }).catch(e => console.log(e))
    }
  }
}
</script>

<style scoped>
body {
  margin: 0;
  padding: 0;
}
</style>